package dao;

import java.util.ArrayList;
import java.util.List;

import hibernate.HibernateUtil;

import org.hibernate.Query;
import org.hibernate.SessionFactory;
import org.hibernate.classic.Session;

import entity.Mesa;
import entity.MesaSimple;
import entity.Sector;

public class MesaDAO {
	private static MesaDAO instancia = null;
	private static SessionFactory sf = null;
	
	private MesaDAO(){
		sf = HibernateUtil.getSessionFactory();
	}
	
	public static MesaDAO getInstancia(){
		if(instancia == null)
			instancia = new MesaDAO();
		return instancia;
	}
	
	public void altaMesa(Mesa mesa){
		try {
			Session session=sf.getCurrentSession();
			session.beginTransaction();
			session.save(mesa);
			session.getTransaction().commit();
		} catch (Exception e){
			System.out.println(e);
			System.out.println("Error MesaDAO. Alta Mesa");
		}
	}
	
	public void mergeMesa(Mesa mesa){
		try {
			Session session=sf.getCurrentSession();
			session.beginTransaction();
			session.merge(mesa);
			session.getTransaction().commit();
		} catch (Exception e){
			System.out.println(e);
			System.out.println("Error MesaDAO. Merge Mesa");
		}
	}
	
	public MesaSimple buscarMesa(int idMesa){
		MesaSimple m = new MesaSimple();
		
		try {
			Session session=sf.getCurrentSession();
			session.beginTransaction();
			m= (MesaSimple) session.createQuery("from MesaSimple m where m.idMesa= :idMesa").setParameter("idMesa", idMesa).uniqueResult();
			session.getTransaction().commit();
		} catch (Exception e) {
			System.out.println(e);
			System.out.println("Error MesaDAO. Buscar Mesa");
		}
		
		return m;
	}
	
	@SuppressWarnings("unchecked")
	public List<MesaSimple> listarMesasLibresPorSector(int idSector) {
		List<MesaSimple> lista=new ArrayList<MesaSimple>();
		
		try {
			Session session=sf.getCurrentSession();
			session.beginTransaction();
			
			Query q=session.createQuery("select M from Sector S join S.mesas M"
					+ " where S.idSector=:idSector and M.estado=:estado");
			q.setParameter("idSector", idSector);
			q.setParameter("estado", "libre");
			lista = q.list();
		
			session.getTransaction().commit();
		} catch (Exception e) {
			System.out.println(e);
			System.out.println("Error MesaDAO. listarMesasLibresPorSector");
		}
		
		return lista;
		
	}

	
}